package com.xuyu.common.tool.fsm;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

public abstract class AbstractFsmEngine<S, E> implements FiniteStateMachine<S, E> {

    private final Map<E, FsmConfigurer<S, E>> registry = new HashMap<>(8);

    @Override
    public void register(FsmConfigurer<S, E> fsmConfigurer) {
        registry.put(fsmConfigurer.getEvent(), fsmConfigurer);
    }

    public FsmConfigurer<S, E> getFireEventConfig(E event) {
        if (registry.containsKey(event)) {
            return registry.get(event);
        }
        return null;
    }

    public AbstractFsmEngine<S, E> add(FsmConfigurer<S, E> fsmConfigurer) {
        register(fsmConfigurer);
        return this;
    }

    @Override
    public List<Function<?, ?>> getHandler(E event) {
        if (registry.containsKey(event)) {
            FsmConfigurer<S, E> secFsmConfigurer = registry.get(event);
            return secFsmConfigurer.getHandlers();
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    public Object fireEvent(E event, Object param) {
        if (event == null) {
            throw new RuntimeException("当前执行的事件为null");
        }
        List<Function<?, ?>> handler = getHandler(event);
        if (handler == null) {
            return null;
        }
        Object res = null;
        for (Function each : handler) {
            res = each.apply(param);
        }
        return res;
    }

}
